<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>简单版单人聊天</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.6.1/sockjs.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.js"></script>
</head>


<body>
<input type="text" id="from" class="form-control" value="hhl2" placeholder="我是">
<input type="text" id="to" class="form-control" value="hhl" placeholder="发送给谁">
内容
<input  id="text" type="text" style="width:500px"/>
<button onclick="send()">发送消息</button>
<button onclick="connect()">建立连接</button>
<button onclick="disconnect()">释放连接</button>
<div id="message"></div>
</body>

<script type="text/javascript">
    var stompClient = null;

    //建立连接
    function connect() {
        var from = document.getElementById('from').value;
        console.log("from="+from)
        var socket = new SockJS('http://127.0.0.1:9999/endpoint-websocket'); //连接上端点(基站)
        stompClient = Stomp.over(socket);           //用stom进行包装，规范协议
        stompClient.connect({}, function (frame) {
            console.log('Connected: ' + frame);
            stompClient.subscribe('/chat/single/'+from, function (result) {
                console.info("result="+result)
                showContent(JSON.parse(result.body));
            });
        });
        alert("连接成功");
    }

    //显示内容
    function showContent(body) {
        console.log(body);
        document.getElementById('message').innerHTML += "接收消息："+body.content+","+body.time + '<br/>';
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        var from = document.getElementById('from').value;
        var to = document.getElementById('to').value;
        stompClient.send("/app/v3/single/chat", {}, JSON.stringify({'content':message,'to':to,'from':from }));
    }

    //释放连接
    function disconnect(){
        if (stompClient !== null) {
            stompClient.disconnect();
            alert("释放连接成功");
        }else{
            alert("释放连接失败");
        }
    }
</script>
</html>